package com.kitty.game.merge;

import com.kitty.common.db.BaseEntityGame;
import com.kitty.common.utils.SpringUtils;
import com.kitty.common.thread.IdGenerator;
import com.kitty.game.ServerService;
import com.kitty.game.config.PetStore;
import com.kitty.game.equip.model.EquipBox;
import com.kitty.game.equip.model.RoleEquip;
import com.kitty.game.friend.model.Friend;
import com.kitty.game.friend.model.FriendBox;
import com.kitty.game.guard.model.Guard;
import com.kitty.game.guard.model.GuardBox;
import com.kitty.game.identity.IdentityType;
import com.kitty.game.market.model.Goods;
import com.kitty.game.party.model.Party;
import com.kitty.game.pet.model.Pet;
import com.kitty.game.pet.model.PetBook;
import com.kitty.game.pet.model.PetBox;
import com.kitty.game.pet.service.BookService;
import com.kitty.game.role.model.Account;
import com.kitty.game.role.model.Role;
import com.kitty.game.role.service.RoleService;
import com.kitty.game.skill.model.RoleSkill;
import com.kitty.game.skill.model.SkillBox;
import com.kitty.game.utils.TimeUtil;
import com.kitty.game.zhenbao.model.Zhenbao;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.json.Json;
import org.nutz.json.JsonFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.ConcurrentHashMap;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

@Service
public class MergeService {
    @Autowired
    ServerService serverService;
    @Autowired
    Dao dao;
    @Autowired
    RoleService roleService;
    @Autowired
    Merge2DBService merge2DBService;
    Logger logger = LoggerFactory.getLogger(getClass());


    /**
     * 角色 装备，宠物，技能，集市，珍宝，宠物仓库，帮派数据
     */
    public void init() {
        if (serverService.getMerge() == 0) {
            return;
        }
        merge2DBService.init();
        HashMap<String, Account> accountHashMap = new HashMap<>();
        HashMap<String, List<String>> account_server = new HashMap<>();
        HashMap<Integer, Integer> old_new = new HashMap<>();
        HashMap<Long, Long> oldUid_newUid = new HashMap<>();
        List<Party> partyList = dao.query(Party.class, Cnd.NEW());
        HashMap<Long, Long> hashMap = new HashMap();
        for (Party party : partyList) {
            long old = party.getId();
            party.setId(IdGenerator.getNextId());
            int count = SpringUtils.getBean(Merge2DBService.class).fetchParty(party);
            if (count > 0) {
                party.setPartyName(party.getPartyName() + "_" + new Random().nextInt(100000));
                insert(party);
            } else {
                insert(party);
            }
            hashMap.put(old, party.getId());
        }
        List<Role> list = dao.query(Role.class, Cnd.where("level", ">", 20));
        HashMap<String, Account> hashMap1 = new HashMap<>();
        List<Account> accounts = dao.query(Account.class, Cnd.NEW());
        for (Account account : accounts) {
            hashMap1.put(account.getId(), account);
        }
        logger.error("角色数量=={}", list.size());
        ArrayList<Role> arrayList = new ArrayList<>();
        for (Role role : list) {
            if (role.getLevel() < 20) {
                continue;
            }
            // 10天没有登录就删除
            if (role.getEnterTime() * 1000 + 10 * TimeUtil.ONE_DAY < System.currentTimeMillis() && role.getTotalCharge() <100) {
                continue;
            }
            int oldroleId = role.getRoleId();
            long oldUid = role.getUid();
            List<Zhenbao> zhenbaoList = dao.query(Zhenbao.class, Cnd.where("roleId", "=", role.getUid()));
            List<Goods> goodsList = dao.query(Goods.class, Cnd.where("roleId", "=", role.getUid()));

            Account account = hashMap1.get(role.getSid());
            if (account == null) {
                logger.error("账号找不到==={}=={}=={}", role.getSid(), role.getName(), role.getRoleId());
                continue;
            }
            Account tempAccount = SpringUtils.getBean(Merge2DBService.class).fetchAccount(account);
            if (tempAccount == null) {
                insert(account);
                accountHashMap.put(account.getId(), account);
            } else {
                if (accountHashMap.get(account.getId()) == null
                        || account_server.get(account.getId()) == null
                        || !account_server.get(account.getId()).contains(role.getDistName())) {
                    long total = new Long(tempAccount.getGold()) + account.getGold();
                    if (total >= 2000000000) {
                        total = 2000000000;
                    }
                    if (total < 0) {
                        total = 0;
                    }
                    tempAccount.setGold((int) total);
                    insert(tempAccount);
                    accountHashMap.put(tempAccount.getId(), tempAccount);
                }
            }
            if (account_server.get(account.getId()) == null) {
                account_server.put(account.getId(), new ArrayList<>());
                account_server.get(account.getId()).add(role.getDistName());
            } else {
                account_server.get(account.getId()).add(role.getDistName());
            }
            role.setRoleId(roleService.getRoleId());
            role.setUid(IdGenerator.getNextId());
//            role.setDistName("双线二区");
//            logger.error("全局唯一ID=={}", role.getUid());
//            logger.error("珍宝数量=={}", zhenbaoList.size());
//            logger.error("集市数量=={}", goodsList.size());
            for (Zhenbao zhenbao : zhenbaoList) {
                zhenbao.setRoleId(role.getUid());
                zhenbao.setId(IdGenerator.getNextId());
                insert(zhenbao);
            }
            for (Goods goods : goodsList) {
                goods.setRoleId(role.getUid());
                goods.setId(IdGenerator.getNextId());
                insert(goods);
            }
            role.setPartyId(hashMap.get(role.getPartyId()) == null ? 0 : hashMap.get(role.getPartyId()));

            int count = SpringUtils.getBean(Merge2DBService.class).fetchRole(role);
            if (count > 0) {
                logger.error("同名角色数量=={}", count);
                role.setName(role.getName() + "_" + new Random().nextInt(100000));
                insert(role);
            } else {
                insert(role);
            }
            old_new.put(oldroleId, role.getRoleId());
            oldUid_newUid.put(oldUid, role.getUid());
            role.doAfterInit();
            arrayList.add(role);
        }

        logger.error("载入装备列表11111=={}", arrayList.toString());
        for (Role role : arrayList) {
            // 所有装备
            HashMap<Integer, Integer> oldequipId_newequipId = new HashMap<>();
            {
                EquipBox equipBox = role.getEquipBox();

                logger.error("载入装备列表=={}", equipBox.toString());

                Map<Integer, RoleEquip> equips = new ConcurrentHashMap<>(equipBox.getEquips());


                equipBox.getEquips().clear();
                for (Map.Entry<Integer, RoleEquip> entry : equips.entrySet()) {
                    int oldequipId = entry.getValue().getId();
                    entry.getValue().setId(SpringUtils.getIdentityService().getNextId(IdentityType.ROLE_EQUIP));
                    entry.getValue().setRoleId(role.getRoleId());
                    equipBox.getEquips().put(entry.getValue().getId(), entry.getValue());
                    oldequipId_newequipId.put(oldequipId, entry.getValue().getId());
                }
            }
            // 守护
            {
                GuardBox guardBox = role.getGuardBox();
                for (Guard guard : guardBox.getGuards()) {
                    guard.setId(SpringUtils.getIdentityService().getNextId(IdentityType.ROLE));
                    guard.setHostId(role.getRoleId());
                }
            }
            // 所有宠物
            HashMap<Integer, Integer> oldpetId_newpetId = new HashMap<>();
            {
                PetBox petBox = role.getPetBox();
                Map<Integer, Pet> allPets = new HashMap<>(petBox.getAllPets());
                petBox.getAllPets().clear();

                for (Map.Entry<Integer, Pet> entry : allPets.entrySet()) {
                    entry.getValue().setId(SpringUtils.getIdentityService().getNextId(IdentityType.ROLE));
                    oldpetId_newpetId.put(entry.getKey(), entry.getValue().getId());
                    entry.getValue().setHostId(role.getRoleId());
                    entry.getValue().setHostName(role.getName());
                    petBox.getAllPets().put(entry.getValue().getId(), entry.getValue());
                }
                Integer integer = oldpetId_newpetId.get(petBox.getFightPetId());
                petBox.setFightPetId(integer == null ? 0 : integer);
                integer = oldpetId_newpetId.get(petBox.getSupplyPetId());
                petBox.setSupplyPetId(integer == null ? 0 : integer);
                integer = oldpetId_newpetId.get(role.getMount());
                role.setMount(integer == null ? 0 : integer);
                // 宠物仓库
                PetStore petStore = petBox.getPetStore();
                HashMap<Short, Integer> petInfo = new HashMap<>(petStore.getPetInfo());
                for (Map.Entry<Short, Integer> entry : petInfo.entrySet()) {
                    integer = oldpetId_newpetId.get(entry.getValue());
                    petStore.getPetInfo().put(entry.getKey(), integer);
                }
                // 宠物天书
                Map<Integer, PetBook> books = new HashMap<>(petBox.getBooks());
                petBox.getBooks().clear();
                for (Map.Entry<Integer, PetBook> entry : books.entrySet()) {
                    entry.getValue().setId(SpringUtils.getBean(BookService.class).getId());
                    integer = oldpetId_newpetId.get(entry.getValue().getPetId());
                    entry.getValue().setPetId(integer == null ? 0 : integer);
                    integer = oldequipId_newequipId.get(entry.getValue().getRoleEquipId());
                    entry.getValue().setRoleEquipId(integer == null ? 0 : integer);
                    petBox.getBooks().put(entry.getValue().getId(), entry.getValue());
                }
            }
            // 好友
            {
                FriendBox friendBox = role.getFriendBox();
                ArrayList<Friend> friends = new ArrayList<>(friendBox.getFriends());
                for (Friend friend : friends) {
                    if (friend.getGid().equals("")) {
                        continue;
                    }
                    Long ll = oldUid_newUid.get(Long.parseLong(friend.getGid()));
                    if (ll != null) {
                        friend.setGid(ll.longValue() + "");
                    } else {
                        logger.error("好友数据找不到=={}", Json.toJson(friend, JsonFormat.compact()));
                    }
                }
            }
            // 技能
            {
                SkillBox skillBox = role.getSkillBox();
                for (Map.Entry<Integer, RoleSkill> entry : skillBox.getSkills().entrySet()) {
                    Integer integer = old_new.get(entry.getValue().getRoleId());
                    if (integer != null) {
                        entry.getValue().setRoleId(integer);
                        continue;
                    }
                    integer = oldpetId_newpetId.get(entry.getValue().getRoleId());
                    if (integer != null) {
                        entry.getValue().setRoleId(integer);
                    }
                }
            }
            role.doBeforeSave();
            insert(role);
        }

    }


    public void insert(BaseEntityGame role) {
        merge2DBService.add2Queue(role);
    }


}
